package com.it.orders.service.impl;
import com.it.common.entity.Cart;
import com.it.common.entity.OrderDetailet;
import com.it.common.entity.Orders;
import com.it.orders.client.CartClient;
import com.it.orders.mapper.OrderDetailetMapper;
import com.it.orders.mapper.OrdersMapper;

import com.it.orders.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Autowired
    private CartClient cartClient;

//    @Override
//    public Integer createOrders(Orders orders) {
//
//        orders.setOrderDate(String.valueOf(LocalDate.now()));
//        ordersMapper.saveOrders(orders);
//        Integer orderId=orders.getOrderId();
//        System.out.println(orderId);
//        for(OrderDetailet od:orders.getList()){
//            od.setOrderId(orderId);
//        }
//        orderDetailetMapper.saveOrderDetailetBatch(orders.getList());
//
//        return orderId;
//    }
@Override
@Transactional
public Integer createOrders(Orders orders) {
    //1、查询当前用户购物车中当前商家的所有食品
    Cart cart = new Cart();
    cart.setUserId(orders.getUserId());
    cart.setBusinessId(orders.getBusinessId());
    List<Cart> cartList = cartClient.listCart(cart);

    //2、创建订单（返回生成的订单编号）
    orders.setOrderDate(String.valueOf(LocalDate.now()));
    ordersMapper.saveOrders(orders);
    int orderId = orders.getOrderId();

    //3、批量添加订单明细
    List<OrderDetailet> list = new ArrayList<>();
    for(Cart c : cartList) {
        OrderDetailet od = new OrderDetailet();
        od.setOrderId(orderId);
        od.setFoodId(c.getFoodId());
        od.setQuantity(c.getQuantity());
        list.add(od);
    }
    orderDetailetMapper.saveOrderDetailetBatch(list);

    //4、从购物车表中删除相关食品信息
    cartClient.removeCart(cart);

    return orderId;
}

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
}
